package swingxrcp.framework.client.application;

import java.io.File;

import swingxrcp.framework.client.Client;
import swingxrcp.framework.client.context.SwingXContext;
import swingxrcp.framework.client.swingx.JXFrame;
import swingxrcp.framework.client.swingx.PageAdvisor;
import swingxrcp.framework.model.domain.Config;
import swingxrcp.framework.model.environment.Environment;
import swingxrcp.framework.util.StringUtils;
import swingxrcp.framework.util.SystemUtils;
import swingxrcp.framework.util.log.Logger;
import swingxrcp.framework.util.log.LoggerFactory;

/**
 * 应用启动入口
 *
 * @author liangfei
 *
 */
public class Application {

	/**
	 * 日志输出接口
	 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	public static JXFrame mainFrame;

	private Console console;

	public void cmdParser(String args) {
	   	if(StringUtils.isEmpty(args)) {
	   		logger.error("没有指定启动属性文件!退出系统...");
    		System.exit(0);
    	}

	   	SwingXContext.SWINGX_CONFIG_FILE = args;

	   	Environment environment = Client.getEnvironment();
		Config config = environment.getCurrentClient().getConfig();
		if (config == null) {
			logger.error("启动属性文件不合法!退出系统...");
			System.exit(0);
		}

		console = new Console(config);

    	/* *** 启动闪屏 *** */
		if (config.isSplash()) {
			console.startSplash();
		}

		initConfig(config);

    	createSpaceModel();

    	loadValidationModel();
	}

	private void initConfig(Config config) {
		SwingXContext.MAIN_FRAME_CLASS = config.getStartClass();// 主框架类
		SwingXContext.DATA_SOURCE = config.getDataSource();// 数据源路径
		SwingXContext.VALIDATION_MODEL = config.getValidatorModel();// 检验模型
	}

    /**
     * 创建空间模型(工作空间)保存数据模型
     *
     * 格式:./workspace/DB/domain
     */
	public void createSpaceModel() {
    	PageAdvisor.showSplashInfo("创建空间模型(工作空间)保存数据模型...");
    	if (StringUtils.isEmpty(SwingXContext.DATA_SOURCE)) {
			SwingXContext.SPACE_MODEL_PATH = SwingXContext.DB_SPACE_MODEL
					+ SystemUtils.getFileSeparator()
					+ SwingXContext.DOMAIN_SPACE_MODEL;
		} else {
			SwingXContext.SPACE_MODEL_PATH = SwingXContext.DATA_SOURCE
					+ SystemUtils.getFileSeparator()
					+ SwingXContext.DB_SPACE_MODEL
					+ SystemUtils.getFileSeparator()
					+ SwingXContext.DOMAIN_SPACE_MODEL;
		}

    	File file = new File(SwingXContext.SPACE_MODEL_PATH);
    	if(!file.exists()) {
    		file.mkdirs();
    	}
	}

    /**
     * 装载校验模型
     *
     */
    private void loadValidationModel() {

    }

	public void run() {
    	PageAdvisor.showSplashInfo("调用控制台启动应用程序...");
		if (console.isStartup()) {
			console.run();
		} else {
			PageAdvisor.showSplashInfo("找不到指定主类或还没有设置主类,退出系统...");
			System.exit(0);
		}
	}
}
